﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using System.IO;
using System.Text;
using System.IO.Compression;
using System.Xml;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace ProjectStudy
{
    public partial class 接口调用 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

            Label1.Text = SinaWeatherInfo("上海");
            string s1 = WeatherInfo("深圳");
            Label2.Text = s1;

            XmlDocument xml = new XmlDocument();
            xml.LoadXml(s1);
            XmlNode xd = xml.SelectSingleNode("//resp");//获取xml文档根节点
            string cityName = xd.SelectSingleNode("city").InnerText;//城市
            string updateTime = xd.SelectSingleNode("updatetime").InnerText;//更新时间
            string temperature = xd.SelectSingleNode("wendu").InnerText;//气温
            string wind = xd.SelectSingleNode("fengli").InnerText;//风力
            string humidity = xd.SelectSingleNode("shidu").InnerText;//湿度
            string windDirection = xd.SelectSingleNode("fengxiang").InnerText;//风向
            string sunRise = xd.SelectSingleNode("sunrise_1").InnerText;//日出时间
            string sunSet = xd.SelectSingleNode("sunset_1").InnerText;//日落时间

            XmlNode environment = xd.SelectSingleNode("environment");//环境节点
            string aqi = environment.SelectSingleNode("aqi").InnerText;//空气污染指数
            string pm25 = environment.SelectSingleNode("pm25").InnerText;//PM2.5
            string suggest = environment.SelectSingleNode("suggest").InnerText;//建议
            string quality = environment.SelectSingleNode("quality").InnerText;//空气质量
            string o3 = environment.SelectSingleNode("o3").InnerText;//臭氧
            string co = environment.SelectSingleNode("co").InnerText;//一氧化碳
            string so2 = environment.SelectSingleNode("so2").InnerText;//二氧化硫
            string no2 = environment.SelectSingleNode("no2").InnerText;//二氧化氮

            XmlNode yesterday = xd.SelectSingleNode("yesterday");//昨日节点
            string date_1 = yesterday.SelectSingleNode("date_1").InnerText;//昨日日期
            string high_1 = yesterday.SelectSingleNode("high_1").InnerText;//昨日最高温
            string low_1 = yesterday.SelectSingleNode("low_1").InnerText;//昨日最低温
            XmlNode day_1 = yesterday.SelectSingleNode("day_1");
            //string type_1 = day_1.SelectSingleNode("type_1").InnerText;//昨日白天天气状态
            string fx_1 = day_1.SelectSingleNode("fx_1").InnerText;//昨日白天风向
            string fl_1 = day_1.SelectSingleNode("fl_1").InnerText;//昨日白天风力
            XmlNode night_1 = yesterday.SelectSingleNode("night_1");
            string type_2 = night_1.SelectSingleNode("type_1").InnerText;//昨日夜间天气状态
            string fx_2 = night_1.SelectSingleNode("fx_1").InnerText;//昨日夜间风向
            string fl_2 = night_1.SelectSingleNode("fl_1").InnerText;//昨日夜间风力

            XmlNode forecast = xd.SelectSingleNode("forecast");//未来五天天气预测节点
            XmlNodeList forecastWeather = forecast.SelectNodes("weather");

            for (int i = 0; i < forecastWeather.Count; i++)
            {
                string date2 = forecastWeather[i].SelectSingleNode("date").InnerText;//日期
                string high2 = forecastWeather[i].SelectSingleNode("high").InnerText;//最高温
                string low2 = forecastWeather[i].SelectSingleNode("low").InnerText;//最低温
                XmlNode day2 = forecastWeather[i].SelectSingleNode("day");
                string type2 = day2.SelectSingleNode("type").InnerText;//白天天气状况
                string fengxiang2 = day2.SelectSingleNode("fengxiang").InnerText;//白天风向
                string fengli2 = day2.SelectSingleNode("fengli").InnerText;//白天风力
                XmlNode night2 = forecastWeather[i].SelectSingleNode("day");
                string type3 = night2.SelectSingleNode("type").InnerText;//夜间天气状况
                string fengxiang3 = night2.SelectSingleNode("fengxiang").InnerText;//夜间风向
                string fengli3 = night2.SelectSingleNode("fengli").InnerText;//夜间风力
            }
            XmlNode zhishus = xd.SelectSingleNode("zhishus");//指数节点
            XmlNodeList zs = zhishus.SelectNodes("zhishu");
            for (int i = 0; i < zs.Count; i++)
            {
                string name = zs[i].SelectSingleNode("name").InnerText;//指数名称
                string sug = zs[i].SelectSingleNode("value").InnerText;//指数建议
                string detail = zs[i].SelectSingleNode("detail").InnerText;//指数详情
            }

            //百世汇通：huitongkuaidi
            //中国邮政：ems
            //邮政小包：youzhengguonei
            //国通快递：guotongkuaidi
            //全峰快递：quanfengkuaidi
            //天天快递：tiantian
            //优速物流：youshuwuliu
            //圆通速递：yuantong
            //韵达快运：yunda
            //中通速递：zhongtong
            //宅急送：zhaijisong
            //顺丰：shunfeng
            //...
            string ss = GetExpressInfo("shunfeng","152395151726");
            JObject jo = (JObject)JsonConvert.DeserializeObject(ss);
            string message = jo["message"].ConvertObjToStr();
            string no = jo["nu"].ConvertObjToStr();
            string company = jo["com"].ConvertObjToStr();

            string state = jo["state"].ConvertObjToStr();
            //0：在途，即货物处于运输过程中；
            //1：揽件，货物已由快递公司揽收并且产生了第一条跟踪信息；
            //2：疑难，货物寄送过程出了问题；
            //3：签收，收件人已签收；
            //4：退签，即货物由于用户拒签、超区等原因退回，而且发件人已经签收；
            //5：派件，即快递正在进行同城派件；
            //6：退回，货物正处于退回发件人的途中；

            string data = jo["data"].ConvertObjToStr();
            JArray array = JArray.Parse(data);

            for (int i = 0; i < array.Count; i++)
            {
                JObject j = JObject.Parse(array[i].ToString());
                string time = j["time"].ConvertObjToStr();//时间
                string context = j["context"].ConvertObjToStr().Replace("【","").Replace("】","");//快件到达位置
                string location = j["location"].ConvertObjToStr().Replace("【", "").Replace("】", "");
            }           
        }

        /// <summary>
        /// 发起一个HTTP请求（以POST方式）
        /// </summary>
        /// <param name="url"></param>
        /// <param name="param"></param>
        /// <returns></returns>
        public static string HttpPost(string url, string param = "")
        {
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.Accept = "*/*";
            request.Timeout = 10000;
            request.AllowAutoRedirect = false;
            StreamWriter requestStream = null;
            WebResponse response = null;
            string responseStr = null;
            try
            {
                requestStream = new StreamWriter(request.GetRequestStream());
                requestStream.Write(param);
                requestStream.Close();
                response = request.GetResponse();
                if (response != null)
                {
                    StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
                    responseStr = reader.ReadToEnd();
                    reader.Close();
                }
            }
            catch (Exception e)
            {
                throw e;
            }
            finally
            {
                request = null;
                requestStream = null;
                response = null;
            }
            return responseStr;
        }

        /// <summary>
        /// 发起一个HTTP请求（以GET方式）
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static string HttpGet(string url)
        {
            WebRequest myWebRequest = WebRequest.Create(url);
            WebResponse myWebResponse = myWebRequest.GetResponse();
            Stream ReceiveStream = myWebResponse.GetResponseStream();
            string responseStr = "";
            if (ReceiveStream != null)
            {
                StreamReader reader = new StreamReader(ReceiveStream, Encoding.UTF8);
                responseStr = reader.ReadToEnd();
                reader.Close();
            }
            myWebResponse.Close();
            return responseStr;
        }

        /// <summary>
        /// 获取天气信息(超详细，还有未来五天天气预报)
        /// </summary>
        /// <param name="city">城市名称</param>
        /// <returns>返回xml格式数据</returns>  
        public string WeatherInfo(string city)
        {
            WebRequest request = WebRequest.Create("http://wthrcdn.etouch.cn/WeatherApi?city="+city); 
            WebResponse response = request.GetResponse();
            GZipStream GStream = new GZipStream(response.GetResponseStream(), System.IO.Compression.CompressionMode.Decompress, true); 
            StreamReader reader = new StreamReader(GStream, Encoding.UTF8); 
            string str = reader.ReadToEnd(); 
            reader.Close(); 
            response.Close();
            return str;
        }

        /// <summary>
        /// 获取新浪天气(仅当日天气)
        /// </summary>
        /// <param name="city">城市名称</param>
        /// <returns>返回xml格式数据</returns>
        public string SinaWeatherInfo(string city)
        {           
            city = HttpUtility.UrlEncode(city, System.Text.Encoding.GetEncoding("gb2312"));
            string url = "http://php.weather.sina.com.cn/xml.php?city=" + city + "&password=DJOYnieT8234jlsK&day=0";
            WebRequest myWebRequest = WebRequest.Create(url);
            WebResponse myWebResponse = myWebRequest.GetResponse();
            Stream ReceiveStream = myWebResponse.GetResponseStream();
            string responseStr = "";
            if (ReceiveStream != null)
            {
                StreamReader reader = new StreamReader(ReceiveStream, Encoding.UTF8);
                responseStr = reader.ReadToEnd();
                reader.Close();
            }
            myWebResponse.Close();
            return responseStr;
        }

        /// <summary>
        /// 获取快递信息
        /// </summary>
        /// <param name="companyId">快递公司ID</param>
        /// <param name="no">运单号</param>
        /// <returns>返回json数据</returns>
        public string GetExpressInfo(string companyId, string no)
        {          
            string url = "http://www.kuaidi100.com/query?show=1&type=" + companyId + "&postid=" + no;

            WebRequest myWebRequest = WebRequest.Create(url);
            WebResponse myWebResponse = myWebRequest.GetResponse();
            Stream ReceiveStream = myWebResponse.GetResponseStream();
            string responseStr = "";
            if (ReceiveStream != null)
            {
                StreamReader reader = new StreamReader(ReceiveStream, Encoding.UTF8);
                responseStr = reader.ReadToEnd();
                reader.Close();
            }
            myWebResponse.Close();
            return responseStr;
        }
    }
}